import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Dropdown, Menu, message, Divider,Form,Input } from 'antd';
import React, { useState, useRef } from 'react';
import { history } from 'umi';
import { connect } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryRole, batchRemoveRole, saveRoleAuthority, queryMenuByRole, addRole, updateRole } from './service';
import CreateForm from './components/CreateForm'
import UpdateForm from './components/UpdateForm'
import RoleForm from './components/RoleForm'
import { HasPermission } from '@/components/AuthComponent/HasPermission';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async selectedRows => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    let result = await batchRemoveRole({
      ids: selectedRows.map(row => row.roleId),
    });
    hide();
    if (result.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    } else {
      message.success(result.message);
      return false;
    }
  } catch (error) {
    console.log('error====>', error)
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const AuthRole = props => {
  const { dispatch, menuList } = props
  const actionRef = useRef();
  const [roleModalVisible, handleRoleModalVisible] = useState(false);
  const [currentRole, handleCurrentRole] = useState({});
  const [checkedKeys, handleCheckedKeys] = useState([]);//权限List check keys
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [formValues, setFormValues] = useState({});
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      initialValue: formValues.roleName || "",
      rules: [
        {
          required: true,
          message: '请输入角色名称',
        },
      ],
    },
    // {
    //   title: '权限',
    //   dataIndex: 'roleSign',
    //   hideInSearch:true,
    // },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
      initialValue: formValues.remark || "",
      valueType: "textarea"
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`role:update`]} type="link" onClick={() => _handleUpdateModalVisible(record)}>编辑</AuthButton>
          <AuthDivider auth={['role:auth', 'role:update']} type="vertical"></AuthDivider>
          <AuthButton auth={['role:auth']} type="link" onClick={() => handlePermissionRole(record)}>授权</AuthButton>
        </>
      ),
    },
  ];

  /**
   * 编辑按钮权限
   * @param {*} record 
   */
  const _handleUpdateModalVisible = async record => {
    handleCurrentRole(record)
    setFormValues(record)
    handleUpdateModalVisible(true)
  }

  /**
   * 新增角色
   * @param {*} fields 
   */
  const handleAdd = async fields => {
    const hide = message.loading('正在添加');
    try {
      let result = await addRole({ ...fields });
      if (result.code === 0) {
        hide();
        message.success('添加成功，即将刷新');
        handleModalVisible(false)
        return true;
      } else {
        hide();
        message.error(result.errmsg);
        return false;
      }
    } catch (error) {
      hide();
      message.error('添加失败，请重试！');
      return false;
    }
  };

  /**
   * 编辑角色
   * @param {*} fields 
   */
  const handleUpdate = async fields => {
    const hide = message.loading('正在编辑');
    try {
      let result = await updateRole({ ...formValues, ...fields });
      if (result.code === 0) {
        hide();
        message.success('编辑成功，即将刷新');
        handleUpdateModalVisible(false)
        setFormValues({})
        return true;
      } else {
        hide();
        message.error(result.errmsg);
        return false;
      }
    } catch (error) {
      hide();
      message.error('编辑失败，请重试！');
      return false;
    }
  };

  /**
   * 配置菜单
   * @param {*} record 
   */
  const handlePermissionRole = async record => {
    dispatch({
      type: 'cubeRole/menusAllList',
      payload: {
        roleId: record.roleId
      }
    })
    let result = await queryMenuByRole({
      roleId: record.roleId
    })
    if (result.code === 0) {
      handleCheckedKeys(result.data.buttonIdList.concat(result.data.menuIdList).map(String))
    }
    handleCurrentRole(record)
    handleRoleModalVisible(true);
  }

  /**
   * 保存配置菜单
   */
  const handleSaveRoleAuthority = async checkedKeys => {
    const hide = message.loading('正在授权');
    if (!currentRole || !currentRole.roleId) return true;
    try {
      let result = await saveRoleAuthority({
        menuIdList: checkedKeys,
        roleId: currentRole.roleId
      });
      hide();
      if (result.code === 0) {
        message.success('授权成功，拥有该权限的用户再次登录生效');
        handleRoleModalVisible(false);
        return true;
      } else {
        message.success(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  }

  /**
   * 编辑
   * @param {*} record 
   */
  const goToEdit = async record => {
    history.push(`/auth/role/update/${props.match.params.id}/${record.id}`);
  };

  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="roleId"
        toolBarRender={(action, { selectedRows }) => [
          <AuthButton auth={[`role:add`]} type="primary" icon={<PlusOutlined />} onClick={() => handleModalVisible(true)}>新增</AuthButton>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      await handleRemove(selectedRows);
                      action.reload();
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                </Menu>
              }
            >
              <AuthButton auth={[`role:batch:delete`]} >批量操作 <DownOutlined /></AuthButton>
            </Dropdown>
          ),
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项
          </div>
        )}
        request={params => {
          let _params = {
            pageNum: params.current,
            ...params,
          }
          delete _params.current
          return queryRole(_params)
        }}
        postData={result => result.list}
        columns={columns}
        rowSelection={{}}
      />
      <RoleForm menuList={menuList} onOk={handleSaveRoleAuthority} onCancel={() => handleRoleModalVisible(false)}
        checkedKeys={checkedKeys} handleCheckedKeys={handleCheckedKeys}
        modalVisible={roleModalVisible} />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          onFinish={async(value)=>{
            const success = await handleAdd(value);

            if (success) {
              handleUpdateModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          autoComplete="off"
        >
          <Form.Item
            label="角色名称"
            name="roleName"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="备注"
            name="remark"
          >
            <Input.TextArea />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </CreateForm>
      <UpdateForm onCancel={() => handleUpdateModalVisible(false)} modalVisible={updateModalVisible}>
      <Form
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{
            roleName:currentRole?.roleName,
            remark:currentRole?.remark
          }}
          onFinish={async(value)=>{
            const success = await handleUpdate(value);

            if (success) {
              handleUpdateModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          autoComplete="off"
        >
          <Form.Item
            label="角色名称"
            name="roleName"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="备注"
            name="remark"
          >
            <Input.TextArea />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </UpdateForm>
    </PageHeaderWrapper>
  );
};

export default connect(({ loading, cubeRole }) => ({
  menuList: cubeRole.menuList
}))(AuthRole);
